
import Taro, { Component } from '@tarojs/taro'
import { View, Swiper, SwiperItem, Image, Text } from '@tarojs/components'
import { observer, inject } from '@tarojs/mobx'
import {
  pageSize,
  formatNumber,
  navigateBack,
  showToast,
  getAvatar,
  subTime,
  navigateTo,
  setStorage
} from "../../utils/common";
import { IStoreProps } from '../../store/Stores'
import { ProductOutput, RecordOutput } from '../../api/api'

import './detail.scss'


interface IHomeProps extends IStoreProps { }

@inject("stores")
@observer
class Index extends Component<IHomeProps> {
  constructor(props){
    super(props)
  }

  state = {
    item: {} as ProductOutput,
    id: '',
    cultOutputs: [] as any[], // 联养周期
    gradeOutputs: [] as any[], // 联养等级
    currentSelect: { cultOutputs: 0, gradeOutputs: 0 },

    pageIndex: 1,
    pageSize: pageSize,
    items: [] as RecordOutput[],
    totalCount: 0,
  }

  componentWillMount() {
    let id = this.$router.params.id
    if(!id) {
      showToast('参数错误~')
      setTimeout(() => { navigateBack() }, 2000)
    }
    this.getItem(id)
    this.setState({ id }, () => {
      this.getBuyLog(id)
    })
  }

  getItem(id: string) {
    let { fishStore } = this.props.stores
    fishStore.productDetails({
      form: { id },
      callback: res => {
        let cultOutputs = res.cultOutputs || []
        cultOutputs.map((item, index) => {
          if(index === 0) { item.isSelect = true }
          else { item.isSelect = false }
        })
        let gradeOutputs = res.gradeOutputs || []
        gradeOutputs.map((item, index) => {
          if(index === 0) { item.isSelect = true }
          else { item.isSelect = false }
        })
        this.setState({ item: res, cultOutputs, gradeOutputs })
      }
    })
  }

  getBuyLog(id: string) {
    let { fishStore } = this.props.stores
    let { pageIndex } = this.state
    fishStore.userOrderRecordPage({
      productId: id,
      pageIndex,
      pageSize: 15,
      callback: res => {
        this.setState({totalCount: res.totalCount, items: res.items})
      }
    })
  }

  link = (url: string) => {
    let { item, gradeOutputs, cultOutputs, currentSelect } = this.state
    if(url.includes('gradeId')){
      // 缓存信息购买页使用
      let profit = cultOutputs[currentSelect.cultOutputs]['proportion'] * 100 + '%' // 收益
      let productDays = cultOutputs[currentSelect.cultOutputs]['cultureDays']// 期限
      let dayId = cultOutputs[currentSelect.cultOutputs]['id']// 期限
      let productNum = gradeOutputs[currentSelect.gradeOutputs]['productQuantity'] // 数量
      let productPrice = gradeOutputs[currentSelect.gradeOutputs]['requireAmount'] // 价格
      let gradeId = gradeOutputs[currentSelect.gradeOutputs]['id'] // 价格
      let productId = item.id // 价格
      setStorage('orderInfo', { ...item, profit, productDays, productNum, productPrice, dayId, gradeId, productId })
    }
    navigateTo(url)
  }

  setCurrentSelect(type: string, index: number) {
    let { currentSelect, cultOutputs, gradeOutputs } = this.state
      if(type === 'cultOutputs') {
        cultOutputs.map((item, ind) => {
          item.isSelect = index === ind;
        })
      }else {
        gradeOutputs.map((item, ind) => {
          item.isSelect = index === ind;
        })
      }
    currentSelect[type] = index
    this.setState({ currentSelect, cultOutputs, gradeOutputs })
  }

  render() {
    let { item, cultOutputs, gradeOutputs, currentSelect, items, totalCount, id } = this.state
    let imgList = item.imgList || ''
    let imgListArr = imgList.split(',')
    let fenzi = item.surplusNumber || 0
    let fenmu = item.productNumber || 0
    let prograssWidth = fenmu === 0 ? '0%' : ((fenzi/fenmu)*100).toFixed(2) + '%'
    let gradeId = gradeOutputs.length>0&&gradeOutputs[currentSelect.gradeOutputs]['id']
    let cultureCycleId = cultOutputs.length>0&&cultOutputs[currentSelect.cultOutputs]['id']
    return (
      <View className='index fish-detail'>
        <View className='integral' />
        <View className=''>
          <Swiper className='swiper-detail' indicatorColor='#eeeeee' indicatorActiveColor='#fff' indicatorDots autoplay={false} circular interval={2000} >
            {
              imgListArr.map(img => {
                if(img) {
                  return (
                    <SwiperItem className='swiper-detail__item' key={img}>
                      <Image className='swiper-detail__img' src={img}/>
                    </SwiperItem>
                  )
                }
              })
            }
          </Swiper>
        </View>

        <View className='list01__item'>
          <View className='list01__info fish-detail__list01__info'>
            <View className='list01__line list01__line-t'>
              <View style={{width: '100%', display: 'flex' }}>
                <Text className='list01__date'>第{formatNumber(item.periodsNum)}期</Text>
                <Text className='list01__title'>{item.comName}</Text>
              </View>
              <View className='list01__share share-icon' style={{display: 'none'}}>分享</View>
            </View>
            <View className='list01__line list01__line-prograss' style={{ width: '100%',position: 'relative',height: '18px' }}>
              <View className='ty'>
                <View className='list01__prograss' />
                <View className='list01__prograss-top' style={{width: prograssWidth}} />
                </View>
              <Text className='list01__percentage'>{prograssWidth}</Text>
            </View>
            <View className='list01__line list01__line-i' style={{marginBottom: '10px'}}>
              <Text className='list01__num'>共{item.productNumber}条</Text>
              <Text className='list01__sy' style={{display: 'none'}}>剩余<Text className='color-theme'>{item.surplusNumber}</Text>条</Text>
            </View>
            <View className='list01__line list01__line-i'>
              <View className='list01__name'>每条 <Text className='list01__name-c yuan'>{item.unitPrice}</Text></View>
             {/* <View className='list01__name'>年收益 <Text className='list01__name-c'>20%</Text></View>
              <View className='list01__name'>期限 <Text className='list01__name-c'>6<Text className='small'>月</Text></Text> </View>*/}
            </View>
          </View>
        </View>
        <View className='column-com' style={{ borderBottom: 'none' }}>
          <View className='column-com__title'>联养数量</View>
        </View>
        <View className='fish-num'>
          <View className='fish-num__num'>
            {
              gradeOutputs.map((sub, index) => {
                return(
                  <Text className={sub.isSelect?'fish-num__con fish-num__con-active':'fish-num__con'} key={sub.id}
                        onClick={this.setCurrentSelect.bind(this, 'gradeOutputs', index)}
                  >{sub.graName}</Text>
                )
              })
            }
          </View>

          {/*<View className='fish-num__set'>
            <View className='fish-num__op'>-</View>
            <Input className='fish-num__input' type='number' />
            <View className='fish-num__op'>+</View>
          </View>*/}
        </View>

        <View className='column-com' style={{ borderBottom: 'none' }}>
          <View className='column-com__title'>联养周期</View>
        </View>

        <View className='fish-num'>
          <View className='fish-num__num'>
            {
              cultOutputs.map((sub, index) => {
                return(
                  <Text className={sub.isSelect?'fish-num__con fish-num__con-active':'fish-num__con'} key={sub.id}
                        onClick={this.setCurrentSelect.bind(this, 'cultOutputs', index)}
                  >{sub.cultureDays}天</Text>
                )
              })
            }
          </View>

          {/*<View className='fish-num__set'>
            <View className='fish-num__op'>-</View>
            <Input className='fish-num__input' type='number' />
            <View className='fish-num__op'>+</View>
          </View>*/}
        </View>
        <View className='interval' />
        <View className='line-common__wrap'>
         {/*  <View className='line-common'>
            <View className='line-common__title'>分润方式</View>
            <View className='line-common__con'>现金分润</View>
          </View> */}
          <View className='line-common'>
            <View className='line-common__title'>联养条数</View>
            <View className='line-common__con color-orange'><Text className='list01__name-c'>{gradeOutputs.length>0&&gradeOutputs[currentSelect.gradeOutputs]['productQuantity']}</Text><Text className='small'>条</Text> </View>
          </View>
        {/*   <View className='line-common'>
            <View className='line-common__title'>预期收益</View>
            <View className='line-common__con color-orange'><Text className='list01__name-c'>{cultOutputs.length>0&&cultOutputs[currentSelect.cultOutputs]['proportion']*100}%</Text></View>
          </View> */}
        </View>

        <View className='interval' />

        {
          items.length>0&&
          <View className='column-com'>
              <View className='column-com__title'>购买记录({totalCount})</View>
              <View className='column-com__more' onClick={this.link.bind(this, '/pages/fish/buyLog?id='+id)}>查看更多 ></View>
          </View>
        }
        {
          items.length>0&&
          <View className='list02'>
            {
              items.map((item, index) => {
                return(
                  <View className='list02__item' key={item.id}>
                    <View className={'list02__id list02__id-top'+index}>{index+1}</View>
                    <Image className='list02__avatar' src={getAvatar(item.avatar)} />
                    <View className='list02__info'>
                      <View className='list02__name'>{item.nickName}</View>
                      <View className='list02__date'>{subTime(item.payTime)}</View>
                    </View>
                    <View className='list02__num'>{item.productQuantity}<Text className='small'>条</Text></View>
                  </View>
                )
              })
            }
          </View>
        }
        {
          items.length<=0&&<View className='desc' style={{ padding: 20 }}>暂时没有相关购买记录~</View>
        }
        <View className='btn-buy btn-buy-disabled'>
          <View className='btn-buy__status'>已售完</View>
        </View>

        <View className='footer-block' />

        <View className='btn-buy'>
          <View className='btn-buy__info'>
            已选 <Text className='color-orange fw'>{gradeOutputs.length>0&&gradeOutputs[currentSelect.gradeOutputs]['productQuantity'] || 0}
          </Text>条鱼,合计：<Text className='color-orange yuan' /><Text className='color-orange fw'>{gradeOutputs.length>0&&(gradeOutputs[currentSelect.gradeOutputs]['requireAmount']) || 0}</Text>
          </View>
          <View className='btn-buy__pay bg-line' onClick={this.link.bind(this,`/pages/fish/buy?gradeId=${gradeId}&cultureCycleId=${cultureCycleId}`)}>立即联养</View>
        </View>
      </View>
    )
  }
}

export default Index
